<template>
  <div class="app-container !p-5">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane :label="$t('email.singleEmailVerification')" name="first">
        <div>
          <el-tag type="warning">{{
            $t('email.emailVerificationWarning')
          }}</el-tag>
        </div>
        <div style="margin-top: 15px">
          <span class="no-padding-input">
            <el-input style="width: 2px">
              <template slot="prepend">{{
                $t('email.verificationProgress')
              }}</template>
            </el-input>
          </span>
          <span class="no-border-radius-input">
            <el-input-number
              v-model="num"
              controls-position="right"
              style="width: 90px"
              @change="handleChange"
              :min="1"
              :max="10"
            ></el-input-number>
          </span>
          <span>
            <el-input
              v-model="emailAddressTemp"
              style="width: 50%; margin: 0px 20px 0px 20px"
              :placeholder="$t('email.needToVerifyEmail')"
            ></el-input>
          </span>
          <span>
            <el-button type="success" @click="handleVerifyEmail">{{
              $t('email.startVerification')
            }}</el-button>
            <el-button type="danger">{{ $t('email.cancelVerify') }}</el-button>
          </span>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('email.batchVerifyEmail')" name="second">
        <div style="height: 220px">
          <div style="margin-right: 20px">
            <el-tag type="warning">{{
              $t('email.batchVerifyEmailTips')
            }}</el-tag>
            <el-button
              :disabled="validating"
              size="mini"
              type="success"
              style="margin-left: 5px; display: inline-block; float: right"
              @click="handleVerifyEmails"
              >{{ $t('email.startVerification') }}</el-button
            >
            <el-button
              size="mini"
              type="primary"
              style="display: inline-block; float: right"
              disabled
              >{{ $t('email.uploadEmail') }}</el-button
            >
          </div>
          <div style="margin-top: 10px">
            <el-input
              type="textarea"
              :autosize="{ minRows: 8, maxRows: 9 }"
              :placeholder="$t('email.typeEmailLineByLine')"
              v-model="emailsAddress"
              style="width: 900px"
            >
            </el-input>
          </div>
        </div>
      </el-tab-pane>
      <div
        class="mt-2.5 mr-5 mb-1.25 px-7.5 py-2.5 border border-solid border-light-500 rounded-md"
      >
        <el-checkbox v-model="configList.databaseCheck" disabled>{{
          $t('email.checkDatabaseBeforeVerifying')
        }}</el-checkbox>
        <el-checkbox v-model="configList.saveToDataBase" disabled>{{
          $t('email.autoSaveResult')
        }}</el-checkbox>
      </div>
    </el-tabs>
    <div class="w-full flex flex-row-reverse py-2">
      <el-button
        type="primary"
        size="small"
        class="!mr-5"
        @click="handleExportValidEmails"
        >导出有效邮箱</el-button
      >
    </div>
    <el-tabs v-model="activeNameFirst" @tab-click="handleClickTab">
      <el-tab-pane :label="$t('email.verifyResults')" name="first-first">
        <div
          style="
            margin: 10px 20px;
            padding: 10px 10px;
            border: 1px solid #e6ebf5;
            height: 72%;
          "
        >
          <el-table
            :data="
              emailAddress.filter(
                (data) =>
                  !searchAddressee ||
                  data.email
                    .toLowerCase()
                    .includes(searchAddressee.toLowerCase())
              )
            "
            class="w-full"
            :height="activeName === 'first' ? '515px' : '375px'"
          >
            <el-table-column :label="$t('email.inbox')" align="center">
              <template slot-scope="scope">
                {{ scope.row.email }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.status')" align="center">
              <template slot-scope="scope">
                <template v-for="item in stateOptions">
                  <template v-if="item['key'] == scope.row.state">
                    <span :class="item.class"
                      ><i :class="item.icon" />{{ item.label }}</span
                    >
                  </template>
                </template>
              </template>
            </el-table-column>
            <el-table-column align="center">
              <template slot="header" slot-scope="scope">
                <el-input
                  v-model="searchAddressee"
                  size="mini"
                  clearable
                  :placeholder="$t('email.enterSearchAddressee')"
                />
              </template>
              <template slot-scope="scope">
                <!-- <el-button size="mini" plain @click="handleSaveToCustomer(scope.row)" :disabled="scope.row.state!==2">保存为客户</el-button> -->
                <el-button
                  size="mini"
                  plain
                  @click="handleEmailRemove(scope.row)"
                  >{{ $t('email.remove') }}</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane name="first-second">
        <span slot="label">{{ $t('email.verificationLog') }}</span>
        <template>
          <el-table
            :data="verifyLogData"
            style="width: 100%"
            :height="activeName === 'first' ? '500px' : '375px'"
          >
            <el-table-column
              :label="$t('common.id')"
              align="center"
              type="index"
            >
            </el-table-column>
            <el-table-column
              prop="emailAddress"
              :label="$t('common.email')"
              align="center"
              min-width="220"
            >
            </el-table-column>
            <el-table-column
              :label="$t('email.effectiveness')"
              align="center"
              min-width="180"
            >
              <template slot-scope="{ row }">
                <template v-if="row.state === true">
                  <span class="state_valid">{{ $t('email.valid') }}</span>
                </template>
                <template v-else>
                  <span class="state_invalid">{{ $t('email.invalid') }}</span>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              min-width="180"
              :label="$t('email.latestUpdateMethod')"
            >
              <template slot-scope="{ row }">
                <template v-if="row.recentlyUpdatedWay">
                  <span>{{ $t('email.active') }}</span>
                </template>
                <template v-else>
                  <span>{{ $t('email.passive') }}</span>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <pagination
          v-show="listQuery.total > 0"
          :total="listQuery.total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          @pagination="getLogList"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import {
  getAction,
  postAction,
  getUrlAction,
  postUrlAction,
  postLongTimeAction,
} from '@/api/common'
import Pagination from '@/components/Pagination/index.vue'
export default {
  name: 'VerifyEmail',
  components: {
    Pagination,
    // TinymcePage
  },
  data: function () {
    return {
      validating: false,
      listQuery: {
        total: 0,
        page: 1,
        limit: 2,
      },
      verifyLogData: [],
      configList: {
        databaseCheck: false,
        saveToDataBase: true,
      },
      emailAddressTemp: '',
      emailsAddressTemp: '',
      emailAddress: [],
      emailsAddress: '',
      searchAddressee: '',
      stateOptions: [
        {
          key: '0',
          label: this.$t('email.toBeVerified'),
          icon: '<i class="el-icon-success" />',
        },
        {
          key: '1',
          label: this.$t('email.verifying'),
          icon: 'el-icon-loading',
          class: 'state_verification',
        },
        {
          key: '2',
          label: this.$t('email.validEmail'),
          icon: 'el-icon-success',
          class: 'state_valid',
        },
        {
          key: '3',
          label: this.$t('email.invalidEmail'),
          icon: 'el-icon-error',
          class: 'state_invalid',
        },
        {
          key: '4',
          label: this.$t('email.saved'),
          icon: 'el-icon-finished',
          class: 'state_save',
        },
      ],
      num: 1,
      sendContentPercentage: 100,
      filterContentPercentage: 50,
      sendSuccessContentPercentage: 80,
      sendFailedContentPercentage: 10,
      activeName: 'first',
      activeNameFirst: 'first-first',
      fileList: [
        {
          name: 'food.jpeg',
          url:
            'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        },
        {
          name: 'food2.jpeg',
          url:
            'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        },
      ],
      form: {
        Title: '',
        Addresser: '',
        ShowAsEmail: false,
        ReplyEmail: '',
        Addressee: [],
        EmailSubject: '{}',
        TimingTransmission: null,
      },
    }
  },
  created() {
    VUE.$on('VerifyEmail', (res) => {
      for (const key in res) {
        const email = this.emailAddress.find((m) => m.email === key)
        if (email) {
          email.state = res[key] ? 2 : 3
          this.creatEmailVerify(res[key], key)
        }
      }
      this.emailAddress = [...this.emailAddress]
    })
  },
  destroyed() {
    VUE.$off('VerifyEmail')
    console.log('destroyed')
  },
  methods: {
    handleClick(tab, event) {
      // console.log(tab, event)
    },
    handleChange(value) {
      // console.log(value)
    },
    handleVerifyEmail() {
      // TODO 验证进程满了的时候，默认状态待验证，验证回调检查是否有未完成的进程，直接取代一个，增加手动验证按钮，只有待验证状态可以使用，通过验证中数量来判断进程数
      console.log('开始验证')
      // 验证 邮箱地址是否符合规范
      const emailAddressTemp = this.emailAddressTemp.trim()
      // 验证是否为空
      if (this.emailAddressTemp.length !== 0) {
        // 验证是否邮箱格式
        if (this.checkEmailAddress(emailAddressTemp)) {
          // 验证是否重复
          const result = this.emailAddress.some((item) => {
            if (item.email === emailAddressTemp) {
              return true
            }
            // TODO: 给出选项是否到数据库查询邮箱已经验证过,此处操作查询邮箱是否已经存在
          })
          if (result) {
            this.$message({
              message: this.$t('email.emailExists'),
              type: 'warning',
            })
            // for (const item in this.userMenus) {
            //   if (this.userMenus[item].id === row.id) {
            //     this.userMenus.splice(item, 1)
            //   }
            // }
          } else {
            // 状态  1验证中 2有效 3无效
            this.emailAddress.push({ email: emailAddressTemp, state: 1 })
            this.emailAddressTemp = ''
            this.launchValidationResults([emailAddressTemp])
          }
        } else {
          this.$message({
            message: this.$t('email.emailIncorrect'),
            type: 'warning',
          })
          return false
        }
      } else {
        this.$message({
          message: this.$t('email.cannotBeEmpty'),
          type: 'warning',
        })
        return false
      }
    },
    handleVerifyEmails() {
      console.log('开始批量验证')
      this.emailsAddressTemp = this.emailsAddress.trim()
      console.log(this.emailsAddressTemp, this.emailsAddressTemp.length)
      if (this.emailsAddressTemp.length !== 0) {
        let emailsAddressTempArray = this.emailsAddressTemp
          .split('\n')
          .map((m) => m.trim())
          .filter((m) => m)
          .filter(this.checkEmailAddress)
        // if (this.checkEmailAddress(emailAddressTemp)) {}
        if (emailsAddressTempArray.length > 0) {
          emailsAddressTempArray = this.$common
            .uniqueArray(emailsAddressTempArray)
            .filter((m) => !this.emailAddress.some((e) => e.email === m))
          this.emailAddress.push(
            ...emailsAddressTempArray.map((m) => ({ email: m, state: 1 }))
          )
          this.emailsAddressTemp = ''
          this.launchValidationResults(emailsAddressTempArray)
        } else {
          this.$message({
            message: this.$t('email.cannotBeEmpty'),
            type: 'warning',
          })
          return false
        }
      } else {
        this.$message({
          message: this.$t('email.cannotBeEmpty'),
          type: 'warning',
        })
        return false
      }
    },
    handleEmailRemove(val) {
      this.emailAddress.splice(
        this.emailAddress.findIndex((i) => i === val),
        1
      )
    },
    handleSaveToCustomer(val) {
      this.$message({
        message: '敬请期待...',
        type: 'warning',
      })
    },
    checkEmailAddress(szMail) {
      const szReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/
      const bChk = szReg.test(szMail)
      console.log(bChk, '111')
      return bChk
    },
    async launchValidationResults(email) {
      console.info('准备验证邮件', email)

      if (this.validating || !email || email.length === 0) {
        return
      }
      this.validating = true
      let i
      let j
      let temp
      const chunk = 5
      for (i = 0, j = email.length; i < j; i += chunk) {
        temp = email.slice(i, i + chunk)
        try {
          await postLongTimeAction({ email: temp }, 'EmailVerify/Verify').then(
            ({ data }) => {
              for (const key in data) {
                const email = this.emailAddress.find((m) => m.email === key)
                if (email) {
                  email.state = data[key] ? 2 : 3
                }
              }
              this.emailAddress = [...this.emailAddress]
            }
          )
        } catch (e) {
          console.error(e)
          for (const key in temp) {
            const email = this.emailAddress.find((m) => m.email === temp[key])
            if (email) {
              email.state = 3
            }
          }
          this.emailAddress = [...this.emailAddress]
        }
      }
      this.validating = false
    },
    creatEmailVerify(state, emailAddress) {
      postAction(
        {
          emailAddress: emailAddress,
          state: state ? 1 : 2,
          recentlyUpdatedWay: true,
        },
        'EmailMarketing/CreatEmailVerify'
      ).then((res) => {
        if (res.code === 20000) {
          console.log('保存到邮箱成功')
        } else {
          this.$message({
            message: this.$t('email.saveToDatabaseFailed'),
            type: 'warning',
          })
        }
      })
    },
    handleClickTab(tab, event) {
      if (tab.name === 'first-second') {
        this.getLogList()
      }
    },
    getLogList() {
      getAction(this.listQuery, 'emailVerify/Index').then((data) => {
        this.listQuery.total = data.data.total
        this.verifyLogData = data.data.items
      })
    },
    /**
     * 导出有效邮箱(txt文本)
     */
    handleExportValidEmails() {
      const validEmails = this.emailAddress?.filter((e) => e.state === 2)
      if (!validEmails || validEmails.length === 0) {
        this.$message.warning('没有有效邮箱')
        return
      }
      const content = validEmails.map((e) => e.email).join('\n')
      const downloadLink = document.createElement('a')
      downloadLink.href = window.URL.createObjectURL(new Blob([content]))
      downloadLink.download = '有效邮箱.txt'
      downloadLink.click()
    },
  },
}
</script>

<style scoped>
.no-padding-input /deep/ .el-input__inner {
  padding: 0px;
  border: unset;
}
.no-border-radius-input /deep/ .el-input__inner {
  border-radius: 0px 4px 4px 0;
  border-top-left-radius: 0px;
  border-bottom-left-radius: 0px;
}
.state_verification {
  color: orange;
}
.state_valid {
  color: green;
}
.state_invalid {
  color: red;
}
.state_save {
  color: rgb(61, 47, 255);
}
</style>
